<template>
  <n-card :bordered="false" class="mt-4 proCard">
    <BasicForm @register="register" @submit="handleSubmit">
      <template #anchorSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
    </BasicForm>
    <BasicTable
      ref="actionRef"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      :summary="createSummary"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #tableTitle>
        <n-button type="primary" @click="add">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          添加
        </n-button>
      </template>
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
      <template #action>
        <TableAction />
      </template>
    </BasicTable>
  </n-card>

  <basicModal ref="modalRef" class="basicModal" @register="modalRegister" @on-ok="okModal">
    <template #default>
      <BasicForm v-if="isEdit" class="basicForm" @register="editRegister" />
      <BasicForm v-else class="basicForm" @register="addRegister" />
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { columns, createSummary } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { useRouter } from 'vue-router';
  import { AddstatisticsDaily, getStatisticsDailyList } from '@/api/statistics/daily';
  import { formatToDate } from '@/utils/dateUtil';
  import { useModal } from '@/components/Modal';
  import { addCloumns, fromSchema } from '@/views/statistics/daily/columns';

  const [register] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 120,
    schemas: fromSchema,
  });

  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const dialog = useDialog();
  const actionRef = ref();
  const isEdit = ref(false);
  const showModal = ref(false);
  const formBtnLoading = ref(false);

  const formParams = reactive({
    userId: 0,
  });

  const params = ref({
    userId: 0,
  });

  function add() {
    openModal();
  }

  const loadDataTable = async (res) => {
    if (!formParams.userId) {
      formParams.userId = 0;
    } else {
      formParams.userId = parseInt(formParams.userId);
    }
    const param = { ...formParams, ...res };
    console.log(param);
    delete param.makeDate;
    return await getStatisticsDailyList(param);
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: '添加',
    width: 600,
  });
  const [addRegister, { submit: addSubmit, setFieldsValue: addSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: addCloumns,
  });

  //提交数据
  async function okModal() {
    await submitAdd();
  }

  async function submitAdd() {
    let formRes = {};
    try {
      formRes = await addSubmit();
    } catch (e) {
      message.error('验证失败，请填写完整信息');
      setSubLoading(false);
    }
    try {
      // formRes.date =
      let params: any = Object.assign({}, formRes);
      params.date = formatToDate(params.date);
      await AddstatisticsDaily(params);
    } finally {
      setSubLoading(false);
    }
    closeModal();
    reloadTable();
    message.success('添加成功');
  }

  function handleDetail(record: Recordable) {
    // console.log('点击了编辑', record);
    // router.push({name: 'rechargeFlow', params: {id: record.userId}});
  }

  function handleSubmit(values: Recordable) {
    console.log('submit', values);
    let tempParams = unref(formParams);
    tempParams = Object.assign(tempParams, values);
    if (values.makeDate) {
      let [startTime, endTime]: [number, number] = values.makeDate;
      let startTimeS = formatToDate(new Date(startTime));
      let endTimeS = formatToDate(new Date(endTime));
      tempParams = Object.assign(tempParams, { startTime: startTimeS, endTime: endTimeS });
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  const exportSorterAndFilterCsv = () =>
    actionRef.value?.downloadCsv({
      fileName: 'sorter-filter',
      keepOriginalData: false,
    });

  onMounted(async () => {
    // const chanList = await getChanList();
    // registChanArray.value = chanList.map((chan) => {
    //   return {
    //     label: chan.chanName,
    //     value: chan.chanId
    //   }
    // });
  });
</script>

<style lang="less" scoped></style>
